package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

// home
func home(w http.ResponseWriter, req *http.Request) {

	//1.接收客户端 request，并将 request 中带的 header 写入 response header
	for k, v := range req.Header {
		w.Header().Del(k)
		for _, vitem := range v {
			w.Header().Add(k, vitem)
		}
	}

	// 2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	key := "VERSION"
	w.Header().Add(key, os.Getenv(key))

	// 3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
	msg := fmt.Sprintf("User from： %s, Status code:　%d\n", getIP(req), http.StatusOK)
	fmt.Println(msg)

	w.WriteHeader(http.StatusOK)
	io.WriteString(w, msg)
}

// healthz 当访问 localhost/healthz 时，应返回200
func healthz(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "200")
}

func main() {
	http.HandleFunc("/", home)
	http.HandleFunc("/healthz", healthz)

	fmt.Println("Start listening server at :80...")
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

// getIP 取IP地址
func getIP(r *http.Request) string {
	IPAddress := r.Header.Get("X-Real-Ip")
	if IPAddress == "" {
		IPAddress = r.Header.Get("X-Forwarded-For")
	}
	if IPAddress == "" {
		IPAddress = r.RemoteAddr
	}
	return IPAddress
}
